<?php
function debug($flag=0){
	$GLOBALS['project_debug']=$flag;
}
function strip_nr($string, $js = false) {
	$string =  str_replace(array(chr(13), chr(10), "\n", "\r", "\t", '  '),array('', '', '', '', '', ''), $string);
	if($js) $string = str_replace("'", "\'", $string);
	return $string;
}
function &get_instance(){
	return Controller::get_instance();
}
function table($name){
	$conf=Conf::getIns();
	$cfg=$conf->load_config('DB');
	return $cfg['prefix'].$name;
}
function load_module(){
	static $module_=array();
	if(empty($module_)) $module_=include(ROOT.'module.inc.php');
	return $module_;
}
function load_pjt($index){
	$return=array();
	$C=Conf::getIns();
	$_pjt_=$C->PJT[$index];
	$return['PROJECT_PATH']=$_pjt_['disk_path'];
	$return['CONTROLLER_DIR']=$return['PROJECT_PATH'].'controllers/';
	$return['SERVICE_DIR']=$return['PROJECT_PATH'].'services/';
	$return['EXP_DIR']=$return['PROJECT_PATH'].'exps/';
	$return['MODEL_DIR']=$return['PROJECT_PATH'].'models/';
	$return['VIEWER_DIR']=$return['PROJECT_PATH'].'viewers/';
	$return['DEFAULT_VIEWER_NAME']='';
	$return['PROJECT_URL']=$C->WEB['url'].$_pjt_['in'];
	$return['PROJECT_CSS_URL']=$C->WEB['url'].$_pjt_['folder'].'/static/css/';
	$return['PROJECT_JS_URL']=$C->WEB['url'].$_pjt_['folder'].'/static/js/';
	$return['PROJECT_IMG_URL']=$C->WEB['url'].$_pjt_['folder'].'/static/images/';
	return $return;
}
function template_files($dir,$prefix=''){
    $files=scandir($dir);
    $return=array();
    foreach((array) $files as $f){
        if($f=='.' or $f=='..') continue;
        if($prefix){
            if(strpos($f,$prefix)!==false) $return[$f]=$f;
        }else{
            $return[$f]=$f;
        }
    }
    return $return;
}
function template($dir,$filename,$def=''){
    $filename or $filename=$def;
    if($filename=='') exit("tpl:no set tpl!");
    if(file_exists($dir.$filename)) return $dir.$filename;
    exit("tpl:{$filename} lost!");
}
function utf8_strlen($string) {
	preg_match_all("/./us", $string, $match);
	return count($match[0]);
}
function kv_builder($arr,$id,$name){
    $res=array();
    foreach((array) $arr as $v) $res[$v[$id]]=$v[$name];
    return $res;
}
function M($name=''){
	if($name==''){
		return new Model;
	}else{
		$f=MODEL_DIR.$name.'Model.class.php';
		if(file_exists($f)){
			include_once($f);
		}else{
			exit($name.'model不存在');
		}
		$class=$name.'Model';
		if(class_exists($class)){
			return new $class;
		}
		exit($class.'model类名无效');
	}
}
function remove_invisible_characters($str, $url_encoded = TRUE){
	$non_displayables = array();
	// every control character except newline (dec 10)
	// carriage return (dec 13), and horizontal tab (dec 09)
	if ($url_encoded){
		$non_displayables[] = '/%0[0-8bcef]/';	// url encoded 00-08, 11, 12, 14, 15
		$non_displayables[] = '/%1[0-9a-f]/';	// url encoded 16-31
	}
	$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';	// 00-08, 11, 12, 14-31, 127
	do{
		$str = preg_replace($non_displayables, '', $str, -1, $count);
	}
	while ($count);
	return $str;
}
function is_php($version = '5.0.0'){
	static $_is_php;
	$version = (string)$version;

	if ( ! isset($_is_php[$version]))
	{
		$_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
	}
	return $_is_php[$version];
}
function addslashes_array($string) { 
	if(is_array($string)){ 
		foreach($string as $key => $val){ 
			$string[$key] = addslashes_array($val); 
		} 
	}else{ 
		$string = addslashes(trim($string)); 
	}
	return $string; 
}
function stripslashes_array($string) {
	if (is_array($string)) {
		foreach ($string as $k => $v) {
			$string[$k] = stripslashes_array($v);
		}
	} else if (is_string($string)) {
		$string = stripslashes($string);
	}
	return $string;
}
function s_i_p($path_array){
	array_unshift($path_array,get_include_path());
	set_include_path(implode(PATH_SEPARATOR,$path_array));
}
function error_404($msg=''){
	header('HTTP/1.1 404 Not Found');
	exit($msg);
}
function load_controller($name,$path=''){
	if($path==''){
		$f=CONTROLLER_DIR.$name.'Controller.class.php';
	}else{
		$f=$path.$name.'Controller.class.php';
	}
	if(file_exists($f)){
		include_once($f);
	}else{
		exit($name.'controller不存在');
	}
	$class=$name.'Controller';
	if(class_exists($class)){
		return new $class;
	}
	exit($class.'controller类名无效');
}
function load_service($name,$path=''){
	if($path==''){
		$f=SERVICE_DIR.$name.'Service.class.php';
	}else{
		$f=$path.$name.'Service.class.php';
	}
	if(file_exists($f)){
		include_once($f);
	}else{
		exit($name.'service不存在');
	}
	$class=$name.'Service';
	if(class_exists($class)){
		return new $class;
	}
	exit($class.'service类名无效');
}
function load_model($name,$path=''){
	if($path==''){
		$f=MODEL_DIR.$name.'Model.class.php';
	}else{
		$f=$path.$name.'Model.class.php';
	}
	if(file_exists($f)){
		include_once($f);
	}else{
		exit($name.'model不存在');
	}
	$class=$name.'Model';
	if(class_exists($class)){
		return new $class;
	}
	exit($class.'model类名无效');
}
//http://www.book.com/admin.php/question/li?block_id=1&page_id=1 k=>v
function current_path($extra=array()){
	parse_str($_SERVER['QUERY_STRING'],$arr);
	return PROJECT_URL.$_SERVER['PATH_INFO'].'?'.http_build_query(array_merge($arr,$extra));
}
function alert($msg){
	echo "<script>alert('{$msg}');</script>";
}
function autoalert($f,$extra=''){
	if($f){
		alert("操作成功！\\n{$extra}");
	}else{
		alert("操作失败！\\n{$extra}");
	}
}
function jump($m,$a,$get='',$p=''){
   //if($p=='') $p=$_SERVER['SCRIPT_NAME'];
   $conf=Conf::getIns();
   $flag=$conf->ENABLE_PATH_INFO;
   if($p=='') $p=PROJECT_URL;
   if($flag){//启用path_info时
		if($get) $get='?'.$get;
		echo "<script>window.location.href='{$p}/{$m}/{$a}{$get}';</script>";
   }else{
		if($get) $get='&'.$get;
		echo "<script>window.location.href='{$p}?m={$m}&a={$a}{$get}';</script>";
   }
   exit;
}
function autojump($get=''){
	jump($_GET['m'],$_GET['a'],$get);
}
function back(){
    echo "<script>window.history.back();</script>";
    exit;
}
function reload($t='parent'){
	if($t=='parent'){
		echo '<script>window.parent.location.reload();</script>';
	}else{
		echo '<script>window.location.reload();</script>';
	}
	exit;
}
function js($code){
	echo '<script>';
	echo $code;
	echo '</script>';
}
function url($m,$a,$get='',$p=''){
	$conf=Conf::getIns();
   $flag=$conf->ENABLE_PATH_INFO;
	if($p=='') $p=PROJECT_URL;
	if($flag){
		if($get) $get='?'.$get;
		return $p."/{$m}/{$a}{$get}";
	}else{
		if($get) $get='&'.$get;
		return $p."?m={$m}&a={$a}{$get}";
	}
}
function md5password($val){
    return md5($val.'what');
}   
//加载js
function loadjs($js,$path='',$tag=1){
    if($path=="") $path=PROJECT_JS_URL;
    if(!is_array($js)){
        $string="<script src='{$path}{$js}.js'></script>\n";
    }else{
        $string='';
        for($i=0;$i<count($js);$i++){
             $string.="<script src='{$path}{$js[$i]}.js'></script>\n";
        }
    }
    if($tag==1){
        echo $string;
    }else{
        return $string;
    }       
}
//加载css
function loadcss($css,$path='',$tag=1){
    if($path=="") $path=PROJECT_CSS_URL;
    if(!is_array($css)){
        $string="<link href='{$path}{$css}.css' rel='stylesheet' type='text/css' />\n";
    }else{
        $string='';
        for($i=0;$i<count($css);$i++){
            $string.="<link href='{$path}{$css[$i]}.css' rel='stylesheet' type='text/css' />\n";
        }
    }
    if($tag==1){
        echo $string;
    }else{
        return $string;
    }                   
}
function p(){
	$args=func_get_args();  //获取多个参数
	if(count($args)<1){
		return;
	}	
	echo '<div style="width:100%;text-align:left"><pre>';
	//多个参数循环输出
	foreach($args as $arg){
		if(is_array($arg)){  
			print_r($arg);
			echo '<br>';
		}else if(is_string($arg)){
			echo $arg.'<br>';
		}else{
			var_dump($arg);
			echo '<br>';
		}
	}
	echo '</pre></div>';	
}
function ip(){
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$ip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}
function myswitch($kvalue,$array){
	return  $array[$kvalue];
}

/*
function load_viewer($name){
	$f=VIEWER_DIR.$name.'.php';
	if(file_exists($f)){
		include($f);
	}else{
		exit($name.'viewer不存在');
	}
}
*/
//二维数组转一维
function multi2single($array){
	$new_array=array();
	$keys=array_keys($array[0]);
	$size=count($keys);
	$n=count($array);
	for($i=0;$i<$n;$i++){
		for($j=0;$j<$size;$j++){
			$key_name=$keys[$j];
			$new_array[$key_name][]=$array[$i][$key_name];
		}
	}
	return $new_array;
}
//二维转一维 单元素
function multi2single_min($array,$key_name){
	$new_array=array();
	if(!is_array($array)) return array();
	if(!is_array($array[0])) return array();
	$n=count($array);
	for($i=0;$i<$n;$i++){
		$new_array[]=$array[$i][$key_name];
	}
	return $new_array;
}
//echo form_radio('tag',array(1=>'显示',0=>'隐藏',2=>'很好'),1);
function form_radio($name,$array,$checked='-1',$id_prefix='x_'){
	$string='';
   foreach($array as $key=>$value){
		if($checked==$key){
			$c="checked='checked'";
		}else{
			$c='';
		}
		$string.=<<<st
\n\r<label><input type="radio" name="{$name}" value="{$key}" {$c} id='{$id_prefix}{$key}' />{$value}</label>
st;
   }
   return $string."\r\n";
}
//echo form_checkbox('mycheckbox',array(0=>'音乐',1=>'体育',2=>'政治'),array(1,2));
function form_checkbox($name,$array,$checked=array(),$id_prefix='y_'){
	$string='';
	foreach($array as $key=>$value){
		if(in_array($key,$checked)){
			$c="checked='checked'";
		}else{
			$c='';
		}
		$string.=<<<st
\n\r<label><input type="checkbox" name="{$name}" value="{$key}" {$c} id='{$id_prefix}{$key}' />{$value}</label>
st;
   }
   return $string."\r\n";
}
//echo form_select(array(0=>'第0个',1=>'第一个',2=>'第二个'),2);
function form_select($array,$selected='-1'){
	$string='';
	foreach($array as $key=>$value){
		if($selected==$key){
			$s="selected='selected'";
		}else{
			$s='';
		}
		$string.=<<<st
\n\r<option value='{$key}' {$s} >{$value}</option>
st;
	}
	return $string."\r\n";
}
function set_cookie($var,$value='',$time=0){
	$conf=Conf::getIns();
	$time=$time>0?$time:(empty($value)?time()-3600:0);
	$var=$conf->cookie_prefix.$var;
	return setcookie($var,$value,$time,$conf->cookie_path,$conf->cookie_domain,$conf->cookie_secure);
}
function get_cookie($var) {
	$conf=Conf::getIns();
	$var=$conf->cookie_prefix.$var;
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : '';
}
function highlight($word,$string,$color='red'){
	return str_replace($word,"<strong style='color:{$color};'>{$word}</strong>",$string);
}
function dsubstr($string, $length, $suffix = '', $start = 0, $charset='utf-8') {
	if($start) {
		$tmp = dsubstr($string, $start);
		$string = substr($string, strlen($tmp));
	}
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array('&quot;', '&lt;', '&gt;'), array('"', '<', '>'), $string);
	$length = $length - strlen($suffix);
	$str = '';
	if(strtolower($charset) == 'utf-8') {
		$n = $tn = $noc = 0;
		while($n < $strlen)	{
			$t = ord($string{$n});
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) break;
		}
		if($noc > $length) $n -= $tn;
		$str = substr($string, 0, $n);
	} else {
		for($i = 0; $i < $length; $i++) {
			$str .= ord($string{$i}) > 127 ? $string{$i}.$string{++$i} : $string{$i};
		}
	}
	$str = str_replace(array('"', '<', '>'), array('&quot;', '&lt;', '&gt;'), $str);
	return $str == $string ? $str : $str.$suffix;
}
function unique(){
	return substr(md5(rand(1000,9999)),5,8);
}
function get_file_type($url){
	if(empty($url)) return '未知';
	$type=strtolower(pathinfo(basename($url),PATHINFO_EXTENSION));
	switch($type){
		case 'gif':
		case 'jpg':
		case 'jpeg':
		case 'png':
		case 'bmp':
		case 'jpg':
		$a='图片';
		break;
		
		case 'doc':
		case 'docx':
		case 'ppt':
		case 'pptx':
		case 'xls':
		case 'xlsx':
		$a='office文档';
		break;
		
		case 'rar':
		case 'zip':
		case '7z':
		$a='压缩文件';
		break;
		
		case 'txt':
		$a='文本文档';
		break;
		
		case 'swf':
		$a='FLASH';
		break;
		
		case 'pdf':
		$a='PDF';
		break;
		
		case 'wma':
		case 'mp3':
		$a='音频';
		break;
		
		case 'wmv':
		case 'flv':
		$a='视频';
		break;
		
		default:
		$a='未知';
		break;
	}
	return $a;
}
function file_viewer($url,$width=false){
	
	$type=strtolower(pathinfo(basename($url),PATHINFO_EXTENSION));
	
	if(in_array($type,array('jpg','jpeg','png','gif','bmp'))){
		$tpl='<img src="{%src%}" width="{%width%}" />';
		$tpl=str_replace(array('{%src%}'),array($url),$tpl);
		
	}else if(in_array($type,array('swf'))){
$tpl='<object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{%width%}" height="300">
  <param name="movie" value="{%src%}" />
  <param name="quality" value="high" />
  <param name="wmode" value="opaque" />
  <param name="swfversion" value="6.0.65.0" />
  <!--[if !IE]>-->
  <object type="application/x-shockwave-flash" data="{%src%}" width="{%width%}" height="300">
    <!--<![endif]-->
    <param name="quality" value="high" />
    <param name="wmode" value="opaque" />
    <param name="swfversion" value="6.0.65.0" />
    <!--[if !IE]>-->
  </object>
  <!--<![endif]-->
</object>';
		$tpl=str_replace(array('{%src%}'),array($url),$tpl);
		
	}else if(in_array($type,array('mp3'))){
$tpl='<object type="application/x-shockwave-flash" data="{%p_js%}dewplayer-vol.swf?mp3={%src%}" width="{%width%}" height="20" id="dewplayer-vol">
	<param name="wmode" value="transparent" />
	<param name="movie" value="{%p_js%}dewplayer-vol.swf?mp3={%src%}" />
	</object>';
		$tpl=$tpl=str_replace(array('{%p_js%}'),array(P_JS),$tpl);
		$tpl=str_replace(array('{%src%}'),array($url),$tpl);
		
	}else if(in_array($type,array('flv'))){
$tpl='<object type="application/x-shockwave-flash" data="{%p_js%}cf_player.swf" width="{%width%}" height="300"><param name="movie" value="{%p_js%}cf_player.swf" /><param name="allowFullScreen" value="true" /><param name="FlashVars" value="autostart=false&id=&fileurl={%src%}" /></object>';
		$tpl=$tpl=str_replace(array('{%p_js%}'),array(P_JS),$tpl);
		$tpl=str_replace(array('{%src%}'),array($url),$tpl);
		
	}else{
		$tpl='<a href="{%src%}" target="_blank" title="{%src%}">下载</a>';
		$tpl=str_replace(array('{%src%}'),array($url),$tpl);
	}
	
	if($width){
		$tpl=str_replace(array('{%width%}'),array($width),$tpl);
	}else{
		$tpl=str_replace(array('{%width%}'),array(''),$tpl);
	}
	return $tpl;
}